home *** CD-ROM | disk | FTP | other *** search
/ isnet Internet / Isnet Internet CD.iso / prog / hiz / 09 / 09.exe / adynware.exe / perl / lib / Benchmark.pm < prev    next >
Encoding:
Perl POD Document  |  1999-12-28  |  9.3 KB  |  358 lines

  1. package Benchmark;
  2.  
  3. =head1 NAME
  4.  
  5. Benchmark - benchmark running times of code
  6.  
  7. timethis - run a chunk of code several times
  8.  
  9. timethese - run several chunks of code several times
  10.  
  11. timeit - run a chunk of code and see how long it goes
  12.  
  13. =head1 SYNOPSIS
  14.  
  15.     timethis ($count, "code");
  16.  
  17.     timethese($count, {
  18.     'Name1' => '...code1...',
  19.     'Name2' => '...code2...',
  20.     });
  21.  
  22.     timethese($count, {
  23.     'Name1' => sub { ...code1... },
  24.     'Name2' => sub { ...code2... },
  25.     });
  26.  
  27.     $t = timeit($count, '...other code...')
  28.     print "$count loops of other code took:",timestr($t),"\n";
  29.  
  30. =head1 DESCRIPTION
  31.  
  32. The Benchmark module encapsulates a number of routines to help you
  33. figure out how long it takes to execute some code.
  34.  
  35. =head2 Methods
  36.  
  37. =over 10
  38.  
  39. =item new
  40.  
  41. Returns the current time.   Example:
  42.  
  43.     use Benchmark;
  44.     $t0 = new Benchmark;
  45.     $t1 = new Benchmark;
  46.     $td = timediff($t1, $t0);
  47.     print "the code took:",timestr($td),"\n";
  48.  
  49. =item debug
  50.  
  51. Enables or disable debugging by setting the C<$Benchmark::Debug> flag:
  52.  
  53.     debug Benchmark 1;
  54.     $t = timeit(10, ' 5 ** $Global ');
  55.     debug Benchmark 0;
  56.  
  57. =back
  58.  
  59. =head2 Standard Exports
  60.  
  61. The following routines will be exported into your namespace
  62. if you use the Benchmark module:
  63.  
  64. =over 10
  65.  
  66. =item timeit(COUNT, CODE)
  67.  
  68. Arguments: COUNT is the number of times to run the loop, and CODE is
  69. the code to run.  CODE may be either a code reference or a string to
  70. be eval'd; either way it will be run in the caller's package.
  71.  
  72. Returns: a Benchmark object.
  73.  
  74. =item timethis ( COUNT, CODE, [ TITLE, [ STYLE ]] )
  75.  
  76. Time COUNT iterations of CODE. CODE may be a string to eval or a
  77. code reference; either way the CODE will run in the caller's package.
  78. Results will be printed to STDOUT as TITLE followed by the times.
  79. TITLE defaults to "timethis COUNT" if none is provided. STYLE
  80. determines the format of the output, as described for timestr() below.
  81.  
  82. =item timethese ( COUNT, CODEHASHREF, [ STYLE ] )
  83.  
  84. The CODEHASHREF is a reference to a hash containing names as keys
  85. and either a string to eval or a code reference for each value.
  86. For each (KEY, VALUE) pair in the CODEHASHREF, this routine will
  87. call
  88.  
  89.     timethis(COUNT, VALUE, KEY, STYLE)
  90.  
  91. =item timediff ( T1, T2 )
  92.  
  93. Returns the difference between two Benchmark times as a Benchmark
  94. object suitable for passing to timestr().
  95.  
  96. =item timestr ( TIMEDIFF, [ STYLE, [ FORMAT ]] )
  97.  
  98. Returns a string that formats the times in the TIMEDIFF object in
  99. the requested STYLE. TIMEDIFF is expected to be a Benchmark object
  100. similar to that returned by timediff().
  101.  
  102. STYLE can be any of 'all', 'noc', 'nop' or 'auto'. 'all' shows each
  103. of the 5 times available ('wallclock' time, user time, system time,
  104. user time of children, and system time of children). 'noc' shows all
  105. except the two children times. 'nop' shows only wallclock and the
  106. two children times. 'auto' (the default) will act as 'all' unless
  107. the children times are both zero, in which case it acts as 'noc'.
  108.  
  109. FORMAT is the L<printf(3)>-style format specifier (without the
  110. leading '%') to use to print the times. It defaults to '5.2f'.
  111.  
  112. =back
  113.  
  114. =head2 Optional Exports
  115.  
  116. The following routines will be exported into your namespace
  117. if you specifically ask that they be imported:
  118.  
  119. =over 10
  120.  
  121. =item clearcache ( COUNT )
  122.  
  123. Clear the cached time for COUNT rounds of the null loop.
  124.  
  125. =item clearallcache ( )
  126.  
  127. Clear all cached times.
  128.  
  129. =item disablecache ( )
  130.  
  131. Disable caching of timings for the null loop. This will force Benchmark
  132. to recalculate these timings for each new piece of code timed.
  133.  
  134. =item enablecache ( )
  135.  
  136. Enable caching of timings for the null loop. The time taken for COUNT
  137. rounds of the null loop will be calculated only once for each
  138. different COUNT used.
  139.  
  140. =back
  141.  
  142. =head1 NOTES
  143.  
  144. The data is stored as a list of values from the time and times
  145. functions:
  146.  
  147.       ($real, $user, $system, $children_user, $children_system)
  148.  
  149. in seconds for the whole loop (not divided by the number of rounds).
  150.  
  151. The timing is done using time(3) and times(3).
  152.  
  153. Code is executed in the caller's package.
  154.  
  155. The time of the null loop (a loop with the same
  156. number of rounds but empty loop body) is subtracted
  157. from the time of the real loop.
  158.  
  159. The null loop times are cached, the key being the
  160. number of rounds. The caching can be controlled using
  161. calls like these:
  162.  
  163.     clearcache($key);
  164.     clearallcache();
  165.  
  166.     disablecache();
  167.     enablecache();
  168.  
  169. =head1 INHERITANCE
  170.  
  171. Benchmark inherits from no other class, except of course
  172. for Exporter.
  173.  
  174. =head1 CAVEATS
  175.  
  176. Comparing eval'd strings with code references will give you
  177. inaccurate results: a code reference will show a slower
  178. execution time than the equivalent eval'd string.
  179.  
  180. The real time timing is done using time(2) and
  181. the granularity is therefore only one second.
  182.  
  183. Short tests may produce negative figures because perl
  184. can appear to take longer to execute the empty loop
  185. than a short test; try:
  186.  
  187.     timethis(100,'1');
  188.  
  189. The system time of the null loop might be slightly
  190. more than the system time of the loop with the actual
  191. code and therefore the difference might end up being E<lt> 0.
  192.  
  193. =head1 AUTHORS
  194.  
  195. Jarkko Hietaniemi <F<jhi@iki.fi>>, Tim Bunce <F<Tim.Bunce@ig.co.uk>>
  196.  
  197. =head1 MODIFICATION HISTORY
  198.  
  199. September 8th, 1994; by Tim Bunce.
  200.  
  201. March 28th, 1997; by Hugo van der Sanden: added support for code
  202. references and the already documented 'debug' method; revamped
  203. documentation.
  204.  
  205. =cut
  206.  
  207. use Carp;
  208. use Exporter;
  209. @ISA=(Exporter);
  210. @EXPORT=qw(timeit timethis timethese timediff timestr);
  211. @EXPORT_OK=qw(clearcache clearallcache disablecache enablecache);
  212.  
  213. &init;
  214.  
  215. sub init {
  216.     $debug = 0;
  217.     $min_count = 4;
  218.     $min_cpu   = 0.4;
  219.     $defaultfmt = '5.2f';
  220.     $defaultstyle = 'auto';
  221.     &disablecache;
  222.     &clearallcache;
  223. }
  224.  
  225. sub debug { $debug = ($_[1] != 0); }
  226.  
  227. sub clearcache    { delete $cache{$_[0]}; }
  228. sub clearallcache { %cache = (); }
  229. sub enablecache   { $cache = 1; }
  230. sub disablecache  { $cache = 0; }
  231.  
  232.  
  233. sub new { my @t = (time, times); print "new=@t\n" if $debug; bless \@t; }
  234.  
  235. sub cpu_p { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $pu+$ps         ; }
  236. sub cpu_c { my($r,$pu,$ps,$cu,$cs) = @{$_[0]};         $cu+$cs ; }
  237. sub cpu_a { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $pu+$ps+$cu+$cs ; }
  238. sub real  { my($r,$pu,$ps,$cu,$cs) = @{$_[0]}; $r              ; }
  239.  
  240. sub timediff {
  241.     my($a, $b) = @_;
  242.     my @r;
  243.     for ($i=0; $i < @$a; ++$i) {
  244.     push(@r, $a->[$i] - $b->[$i]);
  245.     }
  246.     bless \@r;
  247. }
  248.  
  249. sub timestr {
  250.     my($tr, $style, $f) = @_;
  251.     my @t = @$tr;
  252.     warn "bad time value" unless @t==5;
  253.     my($r, $pu, $ps, $cu, $cs) = @t;
  254.     my($pt, $ct, $t) = ($tr->cpu_p, $tr->cpu_c, $tr->cpu_a);
  255.     $f = $defaultfmt unless defined $f;
  256.     $style ||= $defaultstyle;
  257.     $style = ($ct>0) ? 'all' : 'noc' if $style eq 'auto';
  258.     my $s = "@t $style"; # default for unknown style
  259.     $s=sprintf("%2d secs (%$f usr %$f sys + %$f cusr %$f csys = %$f cpu)",
  260.                 @t,$t) if $style eq 'all';
  261.     $s=sprintf("%2d secs (%$f usr %$f sys = %$f cpu)",
  262.                 $r,$pu,$ps,$pt) if $style eq 'noc';
  263.     $s=sprintf("%2d secs (%$f cusr %$f csys = %$f cpu)",
  264.                 $r,$cu,$cs,$ct) if $style eq 'nop';
  265.     $s;
  266. }
  267.  
  268. sub timedebug {
  269.     my($msg, $t) = @_;
  270.     print STDERR "$msg",timestr($t),"\n" if $debug;
  271. }
  272.  
  273.  
  274. sub runloop {
  275.     my($n, $c) = @_;
  276.  
  277.     $n+=0; # force numeric now, so garbage won't creep into the eval
  278.     croak "negative loopcount $n" if $n<0;
  279.     confess "Usage: runloop(number, [string | coderef])" unless defined $c;
  280.     my($t0, $t1, $td); # before, after, difference
  281.  
  282.     my($curpack) = caller(0);
  283.     my($i, $pack)= 0;
  284.     while (($pack) = caller(++$i)) {
  285.     last if $pack ne $curpack;
  286.     }
  287.  
  288.     my $subcode = (ref $c eq 'CODE')
  289.     ? "sub { package $pack; my(\$_i)=$n; while (\$_i--){&\$c;} }"
  290.     : "sub { package $pack; my(\$_i)=$n; while (\$_i--){$c;} }";
  291.     my $subref  = eval $subcode;
  292.     croak "runloop unable to compile '$c': $@\ncode: $subcode\n" if $@;
  293.     print STDERR "runloop $n '$subcode'\n" if $debug;
  294.  
  295.     $t0 = &new;
  296.     &$subref;
  297.     $t1 = &new;
  298.     $td = &timediff($t1, $t0);
  299.  
  300.     timedebug("runloop:",$td);
  301.     $td;
  302. }
  303.  
  304.  
  305. sub timeit {
  306.     my($n, $code) = @_;
  307.     my($wn, $wc, $wd);
  308.  
  309.     printf STDERR "timeit $n $code\n" if $debug;
  310.  
  311.     if ($cache && exists $cache{$n}) {
  312.     $wn = $cache{$n};
  313.     } else {
  314.     $wn = &runloop($n, '');
  315.     $cache{$n} = $wn;
  316.     }
  317.  
  318.     $wc = &runloop($n, $code);
  319.  
  320.     $wd = timediff($wc, $wn);
  321.  
  322.     timedebug("timeit: ",$wc);
  323.     timedebug("      - ",$wn);
  324.     timedebug("      = ",$wd);
  325.  
  326.     $wd;
  327. }
  328.  
  329.  
  330. sub timethis{
  331.     my($n, $code, $title, $style) = @_;
  332.     my $t = timeit($n, $code);
  333.     local $| = 1;
  334.     $title = "timethis $n" unless defined $title;
  335.     $style = "" unless defined $style;
  336.     printf("%10s: ", $title);
  337.     print timestr($t, $style),"\n";
  338.  
  339.     print "            (warning: too few iterations for a reliable count)\n"
  340.     if     $n < $min_count
  341.         || ($t->real < 1 && $n < 1000)
  342.         || $t->cpu_a < $min_cpu;
  343.     $t;
  344. }
  345.  
  346. sub timethese{
  347.     my($n, $alt, $style) = @_;
  348.     die "usage: timethese(count, { 'Name1'=>'code1', ... }\n"
  349.         unless ref $alt eq HASH;
  350.     my @names = sort keys %$alt;
  351.     $style = "" unless defined $style;
  352.     print "Benchmark: timing $n iterations of ",join(', ',@names),"...\n";
  353.  
  354.     map timethis($n, $alt->{$_}, $_, $style), @names;
  355. }
  356.  
  357. 1;
  358.